package me.pppploi8.webmcs.main.urlmapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import me.pppploi8.webmcs.http.jetty.HttpUrlMapping;
import me.pppploi8.webmcs.minecraft.server.core.McServerCore;
import me.pppploi8.webmcs.minecraft.server.core.McServerFactory;
import me.pppploi8.webmcs.minecraft.server.struct.McMessageInterface;

/**
 * WebMCS核心服务，负责对外提供开服核心系列接口
 * @author pppploi8
 */
public class WebmcsCoreService extends HttpUrlMapping{
    private McServerCore msc;
    private static List<String[]> messagePool = null;
    public WebmcsCoreService(){
    	this.msc = McServerFactory.getMcServerCore();
    	if (messagePool == null){
    		messagePool = new ArrayList<>();
    		msc.setMessageNotice(new McMessageInterface() {
    			@Override
    			public void message(String message) {
    				synchronized(messagePool){
    					if (messagePool.size() >= 40){
    						messagePool = messagePool.subList(messagePool.size()-20, messagePool.size());
    					}
    					messagePool.add(new String[]{UUID.randomUUID().toString(),message});
    				}
    			}
    		});
    	}
    }
    /**
     * 获取MC服务端回显消息，如果无则挂起连接直到得到消息为止
     * 每次访问应当带上返回结果中的UUID，以便确定读取消息位置，格式为 uuid={uuid}
     * @return 返回一个JSON，如果服务器关闭，格式为{"status":false}，如果成功，格式为{status:true,uuid:"{uuid}",message:"{message}"}
     */
    public Object message() throws InterruptedException{
        String uuid = getRequest().getParameter("uuid");
        Map<String,Object> returnMap = new TreeMap<>();
        returnMap.put("status",true);
        if (!msc.getServerStatus()){
            returnMap.put("status",false);
        }
        if (uuid != null && !uuid.equals("")){
            int size = messagePool.size();
            if (size > 0 && messagePool.get(size-1)[0].equals(uuid)){
                returnMap.put("uuid", uuid);
                returnMap.put("message", null);
                return returnMap;
            }
            for (int i = messagePool.size()-2; i >= 0 ; --i){
                if (messagePool.get(i)[0].equals(uuid)){
                    //输出uuid后的所有消息并返回最后一条消息
                    String tmp = "";
                    int j;
                    for (j = i+1; j < messagePool.size() ; ++j){
                        tmp += messagePool.get(j)[1];
                    }
                    returnMap.put("uuid", messagePool.get(j-1)[0]);
                    returnMap.put("message", tmp);
                    return returnMap;
                }
            }
        }
        //说明UUID不存在，可能已被清除，则输出全部消息并定位到最后一条
        returnMap.put("uuid", messagePool.isEmpty()?"":messagePool.get(messagePool.size()-1)[0]);
        String returnString = ""; 
        for (String[] strings : messagePool) {
            returnString += strings[1];
        }
        returnMap.put("message", returnString);
        return returnMap;
    }
    /**
     * 开启服务端
     * @return 
     */
    public String start() throws IOException {
        if(msc.getServerStatus()){    
            return "{\"status\":false,\"msg\":\"ALREADYSERVER\"}";
        }else if(!msc.getJarFile().exists() || !msc.getJarFile().isFile()){
            return "{\"status\":false,\"msg\":\"JARERROR\"}";
        }else if(!msc.start()){
            return "{\"status\":false,\"msg\":\"PROCESSERROR\"}";
        }else{
            return "{\"status\":true}";
        }
    }
    /**
     * 关闭服务端
     * @return 
     */
    public String stop() {
        if (!msc.getServerStatus()) {
            return "{\"status\":false,\"msg\":\"SERVERNOTRUN\"}";
        } else if (!msc.stop()) {
            return "{\"status\":false,\"msg\":\"UNKNOWNERROR\"}";
        } else {
            return "{\"status\":true}";
        }
    }
    /**
     * 重启服务端，请注意这会挂起连接，直到重启成功或者失败
     * @return
     */
    public String restart() throws IOException {
        if (!msc.getServerStatus()) {
            return "{\"status\":false,\"msg\":\"SERVERNOTRUN\"}";
        } else if (!msc.restart()) {
            return "{\"status\":false,\"msg\":\"TIMEOUT\"}";
        } else {
            return "{\"status\":true}";
        }
    }
    /**
     * 强制终止服务端，会造成地图回档，慎用
     * @return
     */
    public Object termination(){
        if(!msc.getServerStatus()){    
            return "{\"status\":false,\"msg\":\"SERVERNOTRUN\"}";
        }else if(!msc.termination()){
            return "{\"status\":false,\"msg\":\"SERVERNOTRUN\"}";
        }else{
            return "{\"status\":true}";
        }
    }
    /**
     * 获取服务器状态
     * @return
     */
    public String status(){
        return msc.getServerStatus()?"{\"status\":true,\"serverstate\":true}":"{\"status\":true,\"serverstate\":false}";
    }
    /**
     * 发送命令给服务器
     * 要求传递参数message=内容
     * @return
     */
    public Object send(){
        if(!msc.getServerStatus()){    
            return "{\"status\":false,\"msg\":\"SERVERNOTRUN\"}";
        }else if(!msc.sendMessage(getRequest().getParameter("message"))){
            return "{\"status\":false,\"msg\":\"UNKNOWNERROR\"}";
        }else{
            return "{\"status\":true}";
        }
    }
}


